package com.ytd.smartcanteen.weighting.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.ytd.common.bean.BaseResponse;

import com.ytd.smartcanteen.weighting.MainActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * fragment基础类
 *
 * @author gaoguanchao
 * @since 2023/3/21 0021
 */
public abstract class BaseFragment extends Fragment implements View.OnTouchListener {

    protected MainActivity mActivity;
    protected View mView;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            mActivity = (MainActivity) context;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getLayoutId(), container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mView = view;
        mView.setOnTouchListener(this);
        initView(view);
    }

    protected abstract void initData(View view);

    protected abstract void initView(View view);

    protected abstract int getLayoutId();

    @Override
    public void onStart() {
        super.onStart();
        initData(mView);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(BaseResponse event) {
        onMessageEvent(event);
    }

    public void onMessageEvent(BaseResponse event) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d("fragment", "onHiddenChanged: " + hidden + "--" + this.getClass().getSimpleName());
    }
}
